package cn.qingyun.gis.modules.init.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

public class PageTool {

    public static <T, R> IPage<T> castToBean(IPage<R> from, Class<T> toClass) throws InstantiationException, IllegalAccessException {
        IPage<T> resIPage = new Page<>();
        BeanUtils.copyProperties(from, resIPage);
        List<R> records = from.getRecords();
        List<T> resList = Lists.newArrayList();

        for (R record : records) {
            T res = toClass.newInstance();
            BeanUtils.copyProperties(record, res);
            resList.add(res);
        }
        resIPage.setRecords(resList);

        return resIPage;
    }

    public static <T> IPage<T> memoryPage(List<T> list, Integer pageNo, Integer pageSize) {
        int total = list.size();
        int pages = total / pageSize;

        Page<T> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNo);
        page.setPages(pages);
        page.setTotal(total);

        List<T> result = list.stream().skip((long) pageSize * (pageNo - 1)).limit(pageSize).collect(Collectors.toList());
        page.setRecords(result);

        return page;
    }
}
